package org.atlantis.ymer.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.atlantis.ymer.Disposable;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FlashPolicyServer implements Disposable {

	private Logger log = LoggerFactory.getLogger(FlashPolicyServer.class);

	private Channel serverChannel;
	private ServerBootstrap bootstrap;

	public void start() {
		bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool()));
		bootstrap.setPipelineFactory(new FlashPolicyPipelineFactory());
		bootstrap.setOption("child.keepAlive", true);
		bootstrap.setOption("child.tcpNoDelay", true);
		serverChannel = bootstrap.bind(new InetSocketAddress(843));
		log.info("Ymer FlashPolicyServer started! Listening on 843");
	}

	private class FlashPolicyPipelineFactory implements ChannelPipelineFactory {

		private FlashPolicyDecoder decoder = new FlashPolicyDecoder();
		private FlashPolicyHandler handler = new FlashPolicyHandler();

		@Override
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("flash-policy-decoder", decoder);
			pipeline.addLast("flash-policy-handler", handler);
			return pipeline;
		}
	}

	@Override
	public void dispose() {
		serverChannel.close();
		bootstrap.releaseExternalResources();
	}
}
